package model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ConnectDB
{

    private static Connection connect = null;
    private static Statement state = null;
    private static boolean connectedToDatabase = false;
    private static PreparedStatement prst = null;

    public static Connection getConnect()
    {
        return connect;
    }

    public static Statement getState()
    {
        return state;
    }

    public static PreparedStatement getPrst(String key)
    {
        try
        {
            prst = getConnect().prepareStatement(key);
        }
        catch (SQLException ex)
        {
            Logger.getLogger(ConnectDB.class.getName()).log(Level.SEVERE, null, ex);
        }
        return prst;
    }

    public static boolean connect()
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Config.readConfig();

            String DATABASE_URL = "jdbc:mysql://" + Config.getHostname() + ":" + Config.getPort() + "/db_project_hotel_manager_team_ttq?useUnicode=true&characterEncoding=utf8";
            connect = (com.mysql.jdbc.Connection) DriverManager.getConnection(DATABASE_URL, Config.getUsername(), Config.getPassword());
            state = (Statement) connect.createStatement();

            connectedToDatabase = true;

        }
        catch (ClassNotFoundException | SQLException ex)
        {
            System.out.println("Error in model.ConnecDb.connect" + ex);
            return connectedToDatabase;
        }
        return connectedToDatabase;
    }

    public static void close()
    {
        if (state != null)
        {
            try
            {
                state.close();
            }
            catch (SQLException ex)
            {
                Logger.getLogger(ConnectDB.class.getName()).log(Level.SEVERE, null, ex);
            }
            state = null;
        }

        if (connect != null)
        {
            try
            {
                connect.close();
            }
            catch (SQLException sqlex)
            {
                Logger.getLogger(ConnectDB.class.getName()).log(Level.SEVERE, null, sqlex);
            }
            connect = null;
        }
        if (prst != null)
        {
            try
            {
                prst.close();
            }
            catch (SQLException sqlex)
            {
                Logger.getLogger(ConnectDB.class.getName()).log(Level.SEVERE, null, sqlex);
            }
            prst = null;
        }
    }
}
